from pathlib import Path
import os
from django.conf import settings
from datetime import datetime,timedelta

from django_q.tasks import schedule
from base_utils.logger import scheduler_logger as logger
from django.utils import timezone

def test_run():
    logger.info(f"执行了test_run函数了,{timezone.now().strftime('%Y-%m-%d %H:%M:%S')}")

def api_create_task():
    logger.info("api接口创建的定时任务")

# 对uwsgi.log日志进行重命名和删除的操作
def uwsgi_log_files():
    fmt = "%Y-%m-%d_%H%M%S"
    log_dir = Path(settings.BASE_DIR) / "logs"
    file_list = os.listdir(log_dir)

    # 匹配 uwsgi.log.* 文件
    uwsgi_files = [name for name in file_list if name.startswith("uwsgi.log.")]
    uwsgi_files.sort(reverse=True)

    # 30天前的日期
    date_30_days_ago = datetime.now() - timedelta(days=30)

    date_uwsgi_files = []

    for old_name in uwsgi_files:
        old_file = log_dir / old_name
        pref, suffix = old_name.rsplit(".", 1)
        try:
            # 时间戳文件，转日期
            ts = int(suffix)
            dt = datetime.fromtimestamp(ts)
            new_name = f"{pref}.{dt.strftime(fmt)}"
            new_file = old_file.parent / new_name
            if not new_file.exists():
                old_file.rename(new_file)
            date_uwsgi_files.append(new_name)
        except ValueError:
            # 已经是日期格式的
            try:
                datetime.strptime(suffix, fmt)
                date_uwsgi_files.append(old_name)
            except ValueError:
                continue

    # 删除30天前的日志
    for name in sorted(date_uwsgi_files, reverse=True):
        suffix = name.rsplit(".", 1)[-1]
        try:
            dt = datetime.strptime(suffix, fmt)
            if dt < date_30_days_ago:
                (log_dir / name).unlink(missing_ok=True)
        except ValueError:
            continue